package com.example.util;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;

@NoArgsConstructor(access = lombok.AccessLevel.PRIVATE)
public class JsonUtil {
    private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    private static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    private static final String GMT8 = "GMT+8";
    private static final ObjectMapper OBJECT_MAPPER = getDefaultObjectMapper();

    public static ObjectMapper getDefaultObjectMapper() {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 配置 Jackson 序列化 LocalDateTime、LocalDate、LocalTime 时使用的格式
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN)));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        // 配置 Jackson 反序列化 LocalDateTime、LocalDate、LocalTime 时使用的格式
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATETIME_PATTERN)));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(javaTimeModule).registerModule(new Jdk8Module()).registerModule(new ParameterNamesModule());
        objectMapper.setTimeZone(TimeZone.getTimeZone(GMT8));
        objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATETIME_PATTERN));

        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.disable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS);

        return objectMapper;
    }


    /**
     * Object转json字符串
     */
    public static <T> String toJson(T obj) {
        try {
            if (obj == null) {
                return null;
            } else if (obj instanceof String) {
                return (String) obj;
            } else {
                return OBJECT_MAPPER.writeValueAsString(obj);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * Object转json字符串并格式化美化
     */
    public static <T> String toJsonPretty(T obj) {
        try {
            if (obj == null) {
                return null;
            } else if (obj instanceof String) {
                return (String) obj;
            } else {
                return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * json转object
     */
    @SuppressWarnings("unchecked")
    public static <T> T toBean(String json, Class<T> clazz) {
        try {
            if (StrUtil.isEmpty(json) || clazz == null) {
                return null;
            } else if (clazz.equals(String.class)) {
                return (T) json;
            } else {
                return OBJECT_MAPPER.readValue(json, clazz);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * json转集合
     */
    @SuppressWarnings("unchecked")
    public static <T> T toBean(String json, TypeReference<T> typeReference) {
        try {
            if (StrUtil.isEmpty(json) || typeReference == null) {
                return null;
            } else if (typeReference.getType().equals(String.class)) {
                return (T) json;
            } else {
                return OBJECT_MAPPER.readValue(json, typeReference);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * json转指定类型的列表对象
     */
    public static <T> List<T> toListBean(String json, Class<T> clazz) {
        try {
            if (StrUtil.isEmpty(json) || clazz == null) {
                return Collections.emptyList();
            } else {
                return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
